package com.jourwon.spring.boot.runnable;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.concurrent.TimeUnit;

/**
 * UpdateLockTimeoutTask 类来执行更新锁超时的时间
 *
 * @author JourWon
 * @date 2023/4/27
 */
@Slf4j
public class UpdateLockTimeoutTask implements Runnable {

    private String uuid;
    private String key;
    private RedisTemplate<String, String> redisTemplate;

    public UpdateLockTimeoutTask(String uuid, RedisTemplate redisTemplate, String key) {
        this.uuid = uuid;
        this.key = key;
        this.redisTemplate = redisTemplate;
    }

    @Override
    public void run() {
        // 将以uuid为Key，当前线程Id为Value的键值对保存到Redis中
        redisTemplate.opsForValue().set(uuid, String.valueOf(Thread.currentThread().getId()));
        // 定期更新锁的过期时间
        while (true) {
            redisTemplate.expire(key, 10, TimeUnit.SECONDS);
            try {
                // 每隔10秒执行一次
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                log.error("Thread.sleep() InterruptedException", e);
            }
        }
    }

}
